<template>
	<div class="tinymce-box">
		<Editor v-model="contentValue" :init="init" :disabled="disabled" style="z-index: 20000;" />
		<div id="aaaaa" class="element">
			<el-dialog v-model="show" :destroy-on-close="true" custom-class="dia" :center="true" width="770px"
				class="style">
				<UploadImageS v-model:urls="images" />
				<template #footer>
					<el-button @click="save()">完成</el-button>
				</template>
			</el-dialog>
		</div>


		<el-dialog title="图片管理器" v-model="showImage" @close="showImage=false" :destroy-on-close="true"
			custom-class="dia" width="800px">
			<WMImageManage @onSuccess="successImage" :multiply="true" />

		</el-dialog>
	</div>
</template>

<script>
	import {
		uploadImage,
		uploadFile
	} from '/@/api/upload.js'
	import {
		getEnvs
	} from "/@/utils/envs.js"
	import {
		GLOBAL_DATA
	} from '/@/api/constant'
	//引入tinymce编辑器
	import Editor from '@tinymce/tinymce-vue'

	//引入方式引入node_modules里的tinymce相关文件文件
	import tinymce from 'tinymce/tinymce' //tinymce默认hidden，不引入则不显示编辑器

	import UploadImageS from '/@/components/upload/UploadImages.vue'
	import WMImageManage from '/@/components/from/WMImageManage.vue'
	import {
		getCurrentInstance,
		defineComponent,
		computed,
		nextTick,
		ref,
		unref,
		watch,
		onMounted,
		onDeactivated,
		onActivated,
		onUnmounted,
		reactive,
		toRefs
	} from 'vue';
	export default {
		name: 'TEditor',
		components: {
			Editor,
			UploadImageS,
			WMImageManage
		},
		props: {
			value: {
				type: String,
				default: ''
			},
			disabled: {
				type: Boolean,
				default: false
			},
			plugins: {
				type: [String, Array],
				default: 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount textpattern autosave '
			},
			toolbar: {
				type: [String, Array],
				default: 'fullscreen undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | \
                styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
                table image media charmap emoticons hr pagebreak insertdatetime print preview | code selectall | indent2em lineheight formatpainter axupimgs  axupimgs1'
			},
		},
		setup(props, ctx) {
			var editorPlus;
			const show = ref(false)
			const showImage = ref(false)
			const {
				envStr
			} = getEnvs()
			let base = GLOBAL_DATA[envStr]['image-url'];
			const validateVideo = async (file) => {
				const isMP4 = file.type === 'video/mp4'
				const isLt3M = file.size / 1024 / 1024 < 3

				if (!isMP4) {
					this.$message.error('上传视频必须为 MP4 格式！')

					return false
				}



				return true
			}

			const data = reactive({
				images: [],
				init: {
					language_url: '/static/tinymce/langs/zh_CN.js', //引入语言包文件
					language: 'zh_CN', //语言类型
					base_url: '/static/tinymce',
					skin_url: '/static/tinymce/skins/ui/oxide', //皮肤：浅色
					// skin_url: '/tinymce/skins/ui/oxide-dark',//皮肤：暗色

					plugins: props.plugins, //插件配置
					toolbar: props.toolbar, //工具栏配置，设为false则隐藏
					toolbar_mode: 'sliding',
					// menubar: 'file edit',  //菜单栏配置，设为false则隐藏，不配置则默认显示全部菜单，也可自定义配置--查看 http://tinymce.ax-z.cn/configure/editor-appearance.php --搜索“自定义菜单”

					fontsize_formats: '12px 14px 16px 18px 20px 22px 24px 28px 32px 36px 48px 56px 72px', //字体大小
					font_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;',
					height: 800, //注：引入autoresize插件时，此属性失效
					width: 'auto',
					placeholder: '在这里输入文字',
					branding: false, //tiny技术支持信息是否显示
					resize: false, //编辑器宽高是否可变，false-否,true-高可变，'both'-宽高均可，注意引号
					statusbar: true, //最下方的元素路径和字数统计那一栏是否显示
					elementpath: false, //元素路径是否显示
					image_dimensions: false,

					lineheight_formats: '1 1.1 1.2 1.3 1.4 1.5 1.75 2',


					// content_css: '/banle.css',  //以css文件方式自定义可编辑区域的css样式，css文件需自己创建并引入

					// images_upload_url: '/demo/upimg.php',  //后端处理程序的url
					// images_upload_base_path: '/demo',  //相对基本路径--关于图片上传建议查看--http://tinymce.ax-z.cn/general/upload-images.php
					// 此处为图片上传处理函数，这个直接用了base64的图片形式上传图片，
					// 如需ajax上传可参考https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_handler
					images_upload_handler: (blobInfo, success, failure) => {
						console.log('>>>>近《《《《')
						var formData;
						var file = blobInfo.blob(); //转化为易于理解的file对象				         
						formData = new FormData();
						formData.append('file', file, file.name); //此处与源文档不一样
						uploadImage(formData).then(res => {

							const {
								envStr
							} = getEnvs()
							let base = GLOBAL_DATA[envStr]['image-url'];
							success(base + res.data.url)
						})


					},
					file_picker_types: 'media',
					video_template_callback: data => {
						return `<video width="745" height="420" controls="controls" src=${data.source} />`
					},
					file_picker_callback: (callback, value, meta) => {
						if (meta.filetype === 'media') {

							const input = document.createElement('input')
							input.setAttribute('type', 'file')

							input.onchange = async function() {
								const file = this.files[
									0] // 为 HTMLInputElement 构造函数中的 this，指向 input 实例对象
								const isValid = await validateVideo(file)

								if (isValid) {
									var formData;

									formData = new FormData();
									formData.append('file', file, file.name); //此处与源文档不一样
									uploadFile(formData).then(res => {


										callback(base + res.data.url)
									})
								} else {
									callback()
								}
							}

							input.click()
						}
					},
					setup(editor) {

						editor.ui.registry.addIcon(
							"more-img",
							`<svg viewBox="0 0 1024 1024" width="26" height="26"><path d="M395.264 634.368l-62.976-87.04c-8.192-11.264-22.016-11.264-30.208 0L186.368 707.584c-8.192 11.264-3.584 20.992 11.264 20.992h530.432c14.336 0 19.456-9.216 10.752-20.992L555.52 456.704c-8.704-11.776-22.016-11.264-30.208 0L395.264 634.368z m16.896-262.656c0 28.16 23.04 51.2 51.2 51.2s51.2-23.04 51.2-51.2-23.04-51.2-51.2-51.2-51.2 23.04-51.2 51.2z" p-id="2140"></path><path d="M118.784 244.736h688.128c-7.168 0-12.8-5.632-12.8-12.8v560.64c0-7.168 5.632-12.8 12.8-12.8H118.784c7.168 0 12.8 5.632 12.8 12.8v-560.64c0 6.656-5.632 12.8-12.8 12.8zM80.896 792.064c0 20.992 16.896 38.4 38.4 38.4h688.128c20.992 0 38.4-17.408 38.4-38.4V231.936c0-20.992-16.896-38.4-38.4-38.4h-688.64c-20.992 0-38.4 17.408-38.4 38.4v560.128z" p-id="2141"></path><path d="M832 333.312h79.36c-6.144 0-10.752-4.608-10.752-10.752v466.944c0-5.632 4.608-10.752 10.752-10.752H832c6.144 0 10.752 4.608 10.752 10.752V322.56c0 6.144-5.12 10.752-10.752 10.752z m-31.744 456.192c0 17.408 14.336 31.744 31.744 31.744h79.36c17.408 0 31.744-14.336 31.744-31.744V322.56c0-17.408-14.336-31.744-31.744-31.744H832c-17.408 0-31.744 14.336-31.744 31.744v466.944z" p-id="2142"></path></svg>`
						);
						// 注册一个自定义的按钮
						editor.ui.registry.addButton("axupimgs", {
							icon: `more-img`,
							text: '多图片上传',
							onAction: function(_) {

								show.value = true

								editorPlus = editor

								nextTick(function() {
									document.getElementById('aaaaa').childNodes[1].style
										.zIndex = '190000000'
								})
								//let html='<img src="https://cos.weimahl.com/image/admin/fb48850df0f74861ae9653722359519d5d2z7gdru6.jpg" width="300" height="auto" alt="">'
								//editor.insertContent(html);
							}
						});

						// 注册一个自定义的按钮
						editor.ui.registry.addButton("axupimgs1", {
							icon: `more-img`,
							text: '单图片上传',
							onAction: function(_) {

								editorPlus = editor
								showImage.value = true

							}
						});
					},
				},
				contentValue: props.value
			})
			onMounted(() => {


				//tinymce.init({})
			})


			watch(
				() => [props.value],
				() => {
					data.contentValue = props.value
				}
			)
			watch(
				() => [data.contentValue],
				() => {
					ctx.emit("update:value", data.contentValue)
				}
			)

			onUnmounted(() => {
				destroyTinymce()
			})

			const destroyTinymce = () => {

			}

			const save = () => {

				if (data.images.length == 0) {
					show.value = false
					return
				}
				let html = ''
				data.images.forEach(item => {
					html += '<img src="' + (base + item) +
						'" alt="" style="vertical-align:top;" />'
				})
				editorPlus.insertContent(html);
				data.images = []
				show.value = false

			}

			const successImage = (val) => {

				showImage.value = false
				let html = '<img src="' + (base + val) +
					'" alt="" style="vertical-align:top;" />'

				editorPlus.insertContent(html);
			}

			return {
				...toRefs(data),
				show,
				save,
				showImage,
				successImage
			}

		},


		// watch: {
		//        value (newValue) {
		//            this.contentValue = newValue
		//        },
		//        contentValue (newValue) {
		//            this.$emit('input', newValue)
		//        }
		// },

	}
</script>

<style>
	/deep/.element.style {
		z-index: 122054 !important;
	}

	.tinymce-box {}

	.tox .tox-editor-header {
		z-index: 0 !important;
	}
</style>